package com.zyong.design.pattern.responsibility.case3;

import java.util.Map;
import java.util.List;
import java.util.Comparator;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * @program: zyong-design-pattern
 * @ClassName: HandleChainManager
 * @author: zyong
 * @create: 2024-04-13 13:49
 */
public class HandleChainManager {
    /**
     * 存放责任链上的具体处理类
     * k-具体业务场景名称
     * v-具体业务场景下的责任链集合
     */
    private Map<String, List<IHandler>> handleMap;

    public void setHandleMap(List<IHandler> handlerList) {
        if (CollectionUtils.isEmpty(handlerList)) {
            return;
        }

        handleMap = handlerList
                .stream()
                .sorted(Comparator.comparingInt(h -> AnnotationUtils.findAnnotation(h.getClass(), Duty.class).order()))
                .collect(Collectors.groupingBy(h -> AnnotationUtils.findAnnotation(h.getClass(), Duty.class).type()));
    }

    /**
     * 执行具体业务场景中的责任链集合
     * @param type 对应@Duty注解中的type，可以定义为具体业务场景
     * @param t 被执行的参数
     * @param <T>
     * @param <R>
     * @return
     */
    public <T, R> R executeHandle(String type, T t) {
        List<IHandler> handlers = handleMap.get(type);
        R r = null;
        if (!CollectionUtils.isEmpty(handlers)) {
            for (IHandler<T, R> handler : handlers) {
                r = handler.handler(t);
            }
        }

        return r;
    }
}
